package cc.z8g.browser.ssl

import android.app.AlertDialog
import cc.z8g.browser.R
import android.content.Context
import android.net.http.SslCertificate
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.widget.TextView
import cc.z8g.browser.dialog.BrowserDialog.resizeAndShow

/**
 * Shows an informative dialog with the provided [SslCertificate] information.
 */
fun Context.showSslDialog(info: SslCertificateInfo) {
    val dateFormat = DateFormat.getDateFormat(applicationContext)
    val contentView = LayoutInflater.from(this).inflate(R.layout.dialog_ssl_info, null, false).apply {
        findViewById<TextView>(R.id.ssl_layout_issue_by).text = info.issuedByCommonName
        findViewById<TextView>(R.id.ssl_layout_issue_to).text = info.issuedToOrganizationName?.takeIf(String::isNotBlank) ?: info.issuedToCommonName
        findViewById<TextView>(R.id.ssl_layout_issue_date).text = dateFormat.format(info.issueDate)
        findViewById<TextView>(R.id.ssl_layout_expire_date).text = dateFormat.format(info.expireDate)
    }

    val icon = createSslDrawableForState(info.sslState)

    AlertDialog.Builder(this)
        .setIcon(icon)
        .setTitle(info.issuedToCommonName)
        .setView(contentView)
        .setPositiveButton(R.string.action_ok, null)
        .resizeAndShow()
}
